<?php


/** ensure this file is being included by a parent file */
defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

/**
 * @package	
 */
class HelpDeskHelperHelpDesk 
{
    /**
     * Retrieves the Itemid
     *
     * @access public
     */
	function getItemid( $link = "index.php?option=com_HelpDesk" ) 
	{
		$id = "";
		$database = HelpDeskConfig::getDBO();
		$link = $database->getEscaped( strtolower( $link ) );
		
		$query = "
			SELECT 
				* 
			FROM 
				#__menu
			WHERE 1 
				AND LOWER(`link`) LIKE '%".$link."%'
				AND `published` > '0'
			ORDER BY 
				`link` ASC
		";
	
		$database->setQuery($query);
		if ( $data = $database->loadObject() ) {
			$id = $data->id;		
		}

		return $id;
	}
	
	/**
	 * Returns a list
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function getAdditionalData( $id ) 
	{
		$data = HelpDeskHelperTicket::getAdditionalData( $id );
		return $data;
	}
	
	/**
	 * Returns a ticket status
	 * @param mixed Boolean
	 * @return array
	 */
	function getTicketStatus( $id, $by='id' ) 
	{
		$type = HelpDeskHelperStatus::getType( $id, $by );
		$data = HelpDeskText::_( $type->status );
		return $data;
	}

	/**
	 * Returns a ticket status image
	 * @param mixed Boolean
	 * @return array
	 */
	function getTicketStatusImage( $id, $by='id' ) 
	{
		$data = HelpDeskHelperStatus::getImage( $id, $by );
		return $data;
	}
	
	/**
	 * Returns a list of types
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function getCategories( $parent=0, $published=1 ) 
	{
		$data = HelpDeskHelperCategory::getChildren( $parent, $published );
		return $data;
	}

	/**
	 * Returns a list of types
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function getAllCategories( $published='1' ) 
	{
		$data = HelpDeskHelperCategory::getAll( $published );
		return $data;
	}
	
	/**
	 * Returns lists
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function buildEditLists() 
	{
		// HelpDeskHTML::script( 'joomla.javascript.js', 'includes/js/');	
		$cat_javascript = "onchange=\"switchDisplayDiv( 'cat_', document.adminForm.categoryid.options[document.adminForm.categoryid.selectedIndex].value);\"";
		$cat_options = 'class="inputbox" size="1" '.$cat_javascript;
		$lists['categoryid'] = HelpDeskHelperCategory::getSelectList( 'categoryid', '', $cat_options );
		return $lists;
	}

	/**
	 * Returns lists
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function buildFieldLists() 
	{	
		$categories = &HelpDeskHelperHelpDesk::getAllCategories();
		
		$return = "";
		$return .= '<div id="cat_" style="display:none;">';
		$return .= '</div>';		
		$return .= '<div id="cat_0" style="display:none;">';
		$return .= '</div>';		
		$return .= '<div id="cat_-1" style="display:none;">';
		$return .= '</div>';
		
		for ($i=0; $i<count($categories); $i++) {
			// foreach of the cat's
			$cat = $categories[$i];
			$return .= '<div id="cat_'.$cat->id.'" style="display:none;">';
			
			$fields = HelpDeskHelperHelpDesk::getCategoryFields( $cat->id );
			for ($f=0; $f<count($fields); $f++) 
			{
				$field = $fields[$f];
				$return .= '<table class="userlist">';
				$return .= '<tr>';
	            	$return .= '<td class="title">';
	                  	$return .= intval($field->typeid != 8) ? HelpDeskText::_( $field->title ) : '';
						$isRequired = HelpDeskHelperField::isRequired( $field->id, $cat->id );
						if ($isRequired) { $return .= ' *'; }
					$return .= '</td>';
	                $return .= '<td class="input">';
                    	$return .= HelpDeskHelperField::draw( $field, 'cat'.$cat->id.'_' );
	                $return .= '</td>';
				$return .= '</tr>';
				$return .= '</table>';				
			}
			
			$return .= '</div>';
		}

		return $return;
	}

	/**
	 * Returns a Feedback Rating
	 * @param mixed Boolean
	 * @return array
	 */
	function getFeedbackRating( $id ) {
		switch ($id) {
		  case "5": $return = HelpDeskText::_( 'Great' ); break;
		  case "4": $return = HelpDeskText::_( 'Good' ); break;
		  case "3": $return = HelpDeskText::_( 'Average' ); break;
		  case "2": $return = HelpDeskText::_( 'Poor' ); break;
		  case "1": $return = HelpDeskText::_( 'Unsatisfactory' ); break;
		  default:  $return = HelpDeskText::_( 'Unrated' ); break;
		} // end switch 
		
		return $return;
	}

	/**
	 * Returns a Feedback Rating
	 * @param mixed Boolean
	 * @return array
	 */
	function getFeedbackRatingImage( $num ) {
		if ($num <= '0') 					 { $id = "0"; }
		elseif ($num > '0' && $num < '0.5') { $id = "0"; }
		elseif ($num >= '0.5' && $num <= '1') { $id = "1"; }
		elseif ($num > '1' && $num < '1.5') { $id = "1.5"; }
		elseif ($num >= '1.5' && $num <= '2') { $id = "2"; }
		elseif ($num > '2' && $num < '2.5') { $id = "2.5"; }
		elseif ($num >= '2.5' && $num <= '3') { $id = "3"; }
		elseif ($num > '3' && $num < '3.5') { $id = "3.5"; }
		elseif ($num >= '3.5' && $num <= '4') { $id = "4"; }
		elseif ($num > '4' && $num < '4.5') { $id = "4.5"; }
		elseif ($num >= '4.5' && $num <= '5') { $id = "5"; }
	
		
		switch ($id) {
		  case "5":   $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/great.png' alt='".HelpDeskText::_( 'Great' )."' title='".HelpDeskText::_( 'Great' )."' name='".HelpDeskText::_( 'Great' )."' align='center' border='0'>"; break;
		  case "4.5": $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/great_half.png' alt='".HelpDeskText::_( 'Great' )."' title='".HelpDeskText::_( 'Great' )."' name='".HelpDeskText::_( 'Great' )."' align='center' border='0'>"; break;
		  case "4":   $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/good.png' alt='".HelpDeskText::_( 'Good' )."' title='".HelpDeskText::_( 'Good' )."' name='".HelpDeskText::_( 'Good' )."' align='center' border='0'>"; break;
		  case "3.5": $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/good_half.png' alt='".HelpDeskText::_( 'Good' )."' title='".HelpDeskText::_( 'Good' )."' name='".HelpDeskText::_( 'Good' )."' align='center' border='0'>"; break;
		  case "3":   $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/average.png' alt='".HelpDeskText::_( 'Average' )."' title='".HelpDeskText::_( 'Average' )."' name='".HelpDeskText::_( 'Average' )."' align='center' border='0'>"; break;
		  case "2.5": $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/average_half.png' alt='".HelpDeskText::_( 'Average' )."' title='".HelpDeskText::_( 'Average' )."' name='".HelpDeskText::_( 'Average' )."' align='center' border='0'>"; break;
		  case "2":   $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/poor.png' alt='".HelpDeskText::_( 'Poor' )."' title='".HelpDeskText::_( 'Poor' )."' name='".HelpDeskText::_( 'Poor' )."' align='center' border='0'>"; break;
		  case "1.5": $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/poor_half.png' alt='".HelpDeskText::_( 'Poor' )."' title='".HelpDeskText::_( 'Poor' )."' name='".HelpDeskText::_( 'Poor' )."' align='center' border='0'>"; break;
		  case "1":   $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/unsatisfactory.png' alt='".HelpDeskText::_( 'Unsatisfactory' )."' title='".HelpDeskText::_( 'Unsatisfactory' )."' name='".HelpDeskText::_( 'Unsatisfactory' )."' align='center' border='0'>"; break;
		  default:    $return = "<img src='".HelpDeskUrl::root()."/components/com_helpdesk/images/feedback/unrated.png' alt='".HelpDeskText::_( 'Unrated' )."' title='".HelpDeskText::_( 'Unrated' )."' name='".HelpDeskText::_( 'Unrated' )."' align='center' border='0'>"; break;
		} // end switch
		
		return $return;

	}	

	/**
	 * Returns an array of user objects
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function getCategoryManagers( $id ) 
	{
		$data = HelpDeskHelperCategory::getManagers( $id );
		return $data;
	}

	/**
	 * Returns yes/no
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function isCategoryManager( $catid, $userid ) 
	{
		$data = HelpDeskHelperManager::isCategory( $userid, $catid );
		return $data;
		
	}

	/**
	 * Returns an array of field objects
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function &getCategoryFields( $id ) 
	{
		$data = HelpDeskHelperCategory::getFields( $id );
		return $data;
	}

	/**
	 * Returns yes/no
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function isCategoryField( $categoryid, $fieldid, $returnObject='0' ) 
	{
		$data = HelpDeskHelperCategory::isField( $categoryid, $fieldid, $returnObject );
		return $data;		
	}
		
	/**
	 * Returns a list of attachments
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function getTicketAttachments( $id ) 
	{
		$data = HelpDeskHelperTicket::getAttachments( $id );
		return $data;
	}

	/**
	 * Shows attachment
	 * @param object Valid file object
	 * @param mixed Boolean
	 * @return array
	 */
	function viewAttachment( $file ) {
		$success = false;
		
		$bfile = new HelpDeskFile();
		if ($file->fileisblob == '1') {
			$file->filedestination = $bfile->blobToFile( $file );			
		} else {
			$dir = $bfile->getDirectory();
			$file->filedestination = $dir.DS.$file->physicalname;
		}

		//This will set the Content-Type to the appropriate setting for the file
		switch( $file->fileextension ) {
			 case "pdf": $ctype="application/pdf"; break;
			 case "exe": $ctype="application/octet-stream"; break;
			 case "zip": $ctype="application/zip"; break;
			 case "doc": $ctype="application/msword"; break;
			 case "xls": $ctype="application/vnd.ms-excel"; break;
			 case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
			 case "gif": $ctype="image/gif"; break;
			 case "png": $ctype="image/png"; break;
			 case "jpeg":
			 case "jpg": $ctype="image/jpg"; break;
			 case "mp3": $ctype="audio/mpeg"; break;
			 case "wav": $ctype="audio/x-wav"; break;
			 case "mpeg":
			 case "mpg":
			 case "mpe": $ctype="video/mpeg"; break;
			 case "mov": $ctype="video/quicktime"; break;
			 case "avi": $ctype="video/x-msvideo"; break;
		
			 //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
			 case "php":
			 case "htm":
			 case "html": if ($file->filedestination) die("<b>Cannot be used for ". $file->fileextension ." files!</b>"); 
		
			 // default: $ctype="application/force-download";
			 default: $ctype="application/octet-stream";	 
		}
		
        // If requested file exists
        if (file_exists($file->filedestination)){
		
            // Fix IE bug [0]
            $header_file = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ? preg_replace('/\./', '%2e', $file->filename, substr_count($file->filename, '.') - 1) : $file->filename;
            // Prepare headers
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: public", false);
            header("Content-Description: File Transfer");
            header("Content-Type: " . $ctype);
            header("Accept-Ranges: bytes");
            header("Content-Disposition: attachment; filename=\"" . $header_file . "\";");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: " . filesize($file->filedestination));

			//ob_end_flush();
			ob_clean();
    		flush();
			readfile($file->filedestination);
			$success = true;
			exit;

        }
		
		return $success;
		
	}
	
	/**
	 * Returns true if user can/not view
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function canViewTicket( $id, $userid ) 
	{
		$data = HelpDeskHelperTicket::canView( $id, $userid );
		return $data;
	}	

	/**
	 * Returns true if user can/not view
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function canViewAttachment( $fileid, $ticketid, $userid ) 
	{
		$data = HelpDeskHelperTicket::canViewAttachment( $ticketid, $userid, $fileid );
		return $data;
	}

	/**
	 * Retrieves the values
	 * @return array Array of objects containing the data from the database
	 */
	function getNameDisplay() 
	{
		static $instance;
		
		if (!is_array($instance)) {
			$instance = array();
				$instance[0] = new stdClass();
				$instance[0]->id = 1;
				$instance[0]->title = 'Name';

				$instance[1] = new stdClass();
				$instance[1]->id = 2;
				$instance[1]->title = 'Username';
				
				$instance[2] = new stdClass();
				$instance[2]->id = 3;
				$instance[2]->title = 'Email';
		}

		return $instance;
	}
	
	/**
	 * Creates a List
	 * @return array Array of objects containing the data from the database
	 */
	function getArrayListNameDisplay() {
		static $instance;
		
		if (!is_array($instance)) {
			$instance = array();
			$data = &HelpDeskHelperHelpDesk::getNameDisplay();
			for ($i=0; $i<count($data); $i++) {
				$d = $data[$i];
		  		$instance[] = mosHTML::makeOption( $d->id, HelpDeskText::_( $d->title ) );
			}
		}

		return $instance;

	}

	/**
	 * Returns a list of attachments
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function getOldTicketAttachments( $days_old ) {
		$database = &HelpDeskConfig::getDBO();

		$where = array();
		$lists = array();

		$date_query = " AND t.datetime < DATE_SUB(CURDATE(),INTERVAL ".intval($days_old)." DAY) ";
	
		// all records		
		$query = "SELECT t.* FROM #__helpdesk_files AS t "
		. " WHERE 1 "
		. $date_query
		;

		$database->setQuery( $query );
		$data = $database->loadObjectList();
		
		return $data;
	}

	/**
	 * Returns value
	 * @param mixed Boolean
	 * @param mixed Boolean
	 * @return array
	 */
	function getOldTicketAttachmentsSizeondisk( $days_old ) {
		$database = &HelpDeskConfig::getDBO();
		$return = "";
		$oldfiles = HelpDeskHelperHelpDesk::getOldTicketAttachments( $days_old );
	
		$file = new HelpDeskFile();
		$dir = $file->getDirectory();
		$sizeondisk = 0;
		
		// foreach one, if file exists, add it
		for ($i=0; $i<count($oldfiles); $i++) {
			$thisfile = $oldfiles[$i];
			if ($fileexists = &JFile::exists( $dir.DS.$thisfile->physicalname)) {
				$sizeondisk = $sizeondisk + filesize( $dir.DS.$thisfile->physicalname );
			}
		}
		
		$return = $sizeondisk/1024;	
		return $return;
	}
			
}

?>